package com.onlineshopping.controller;

import com.onlineshopping.entity.Item;
import com.onlineshopping.entity.Result;
import com.onlineshopping.entity.User;
import com.onlineshopping.service.MailService;
import com.onlineshopping.service.UserService;
import com.onlineshopping.utils.JwtTokenUtil;
import com.onlineshopping.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author laisir
 * @date 2024/8/28
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    private final MailService mailService;
    @Autowired
    private UserController(MailService mailService) {
        this.mailService = mailService;
    }

    @PostMapping("/login")
    public Result<?> login(@RequestBody User user, HttpSession session) {
        String token = userService.login(user);
        Map<String, Object> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);
        tokenMap.put("state", true);
        session.setAttribute("username", user.getUsername());
        return Result.success(tokenMap);
    }

    @GetMapping("/test")
    public String test() {
        return "test";
    }

    @PostMapping("/sendEmail")
    public String sendEmail(@RequestBody UserVo userVo, HttpSession httpSession) {
        String email = userVo.getEmail();
        boolean flag = mailService.sendMail(email, httpSession);
        //System.out.println(httpSession.getId());
        if (!flag) return "发送失败";
        return "发送成功";
    }

    @PostMapping("/register")
    public String register(@RequestBody UserVo userVo, HttpSession httpSession) {;
        //System.out.println(userVo);
        boolean flag = mailService.register(userVo, httpSession);
        if (!flag) return "注册失败";
        return "注册成功";
    }

    @PostMapping("/logout")
    public String logout(HttpSession httpSession) {
        String username = (String) httpSession.getAttribute("username");
        if (username == null) {
            return "用户未登录";
        }
        // 从会话中移除用户信息
        log.info("用户{}已注销", username);
        httpSession.removeAttribute("username");
        // 使会话无效，清除所有会话数据
        httpSession.invalidate();
        // 返回登出成功的消息
        return "登出成功";
    }

    @PostMapping("/verifyCode")
    public Result<?> verifyCode(@RequestBody UserVo userVo, HttpSession httpSession) {
        String code = (String) httpSession.getAttribute("code");
        Long expiration = (Long) httpSession.getAttribute("expiration");
        if (code == null || expiration == null || System.currentTimeMillis() > expiration) {
            return Result.error("验证码已过期");
        }
        if (!code.equals(userVo.getCode())) {
            return Result.success("验证码错误");
        }
        return Result.success("验证码正确");
    }

    @PostMapping("/resetPassword")
    public Result<?> resetPassword(@RequestBody UserVo userVo) {
        User user = userVo.toUser();
        userService.resetPassword(user);
        return null;
    }

    @GetMapping("/profile")
    public List<String> getProfile(HttpServletRequest request) {
        String authHeader = request.getHeader("Authorization");
        String authToken = authHeader.substring(6);
        String username = JwtTokenUtil.getUserNameFromToken(authToken);
        if (username == null) {
            throw new RuntimeException("Username is null.");
        }
        String address = userService.getProfile(username);
        if (address == null) address = "未填写";
        return List.of(new String[]{username, address});
    }

    @PutMapping("/updateSetting")
    public boolean updateSetting(@RequestBody User user, HttpServletRequest request) {
        String authHeader = request.getHeader("Authorization");
        String authToken = authHeader.substring(6);
        String oldUsername = JwtTokenUtil.getUserNameFromToken(authToken);
        if (oldUsername == null) {
            throw new RuntimeException("Username is null.");
        }
        String username = user.getUsername();
        String address = user.getAddress();
        return userService.updateSetting(username, address, oldUsername);
    }

    @GetMapping("/users")
    public List<User> getAll(){
        return userService.getAll();
    }

    @DeleteMapping("/deleteUser/{uid}")
    public String deleteUser(@PathVariable Long uid){
        System.out.println(uid);
        // 处理删除逻辑
        userService.deleteUser(uid);
        return "User deleted successfully";
    }
}
